import { useDrop } from "react-dnd";
import { useComponentConfigStore } from "@/stores/low-editor-comps-conf";
import { getComponentById, useComponentsStore, ComponentUnitType } from "@/stores/edit-pages-store";
import { getNanoid } from "@/utils/common";


export interface ItemType {
  type: string;
  id: string;
  dragType?: 'move' | 'add';
  containerUnitType?: ComponentUnitType //在dragType ==='move'的时候需要
}
export function useMaterialDrop(accept: string[], id: string, containerUnitType: ComponentUnitType="body") {
  const { addComponent,deleteComponent,schema } = useComponentsStore();
  const { flatComponentConfig } = useComponentConfigStore();
  const componentConfig = flatComponentConfig()
  
  const [{ canDrop }, drop] = useDrop(() => ({
    accept,
    drop: (item: ItemType, monitor) => {
      const didDrop = monitor.didDrop();
      if (didDrop) {
        return;
      }
      if(item.dragType === 'move'){
        const component = getComponentById(item.id, schema)!;
        if(component.id === id)return
        deleteComponent(item.id, item.containerUnitType);
        addComponent(component, id, containerUnitType);
      }else{
        const config = componentConfig[item.type];
        const cid = getNanoid();
        const defaultProps = typeof config.defaultProps === 'function' ? config.defaultProps() : config.defaultProps;
        addComponent(
          {
            id: cid,
            name: item.type,
            props: defaultProps,
            desc: config.desc,
            alias: config.alias,
            styles: config.defaultStyles,
            body: config?.getBody?.(cid),
            footer: config?.getFooter?.(cid)
          },
          id,
          containerUnitType
        );
      }
    },
    collect: monitor => ({
      canDrop: monitor.canDrop(),
    }),
  }));

  return { canDrop, drop };
}
